﻿#region License

// Another free, open solution by folks who get it.
// Copyright © 2011 Business in Unison, Inc.
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#endregion

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

using Patterns.Collections;
using Patterns.IO;
using Patterns.SafeCode;

namespace Patterns.Data
{
	/// <summary>
	/// 	Defines ease-of-use extensions to the <see cref = "IDataRecord" /> type.
	/// </summary>
	public static class DataRecordExtensions
	{
		private static readonly long _dataBufferSize = FileSize.FromMegabytes(1);

		private static readonly IDictionary<Type, Func<IDataRecord, int, object>> _valueGetters =
			new Dictionary<Type, Func<IDataRecord, int, object>>
			{
				{ typeof (bool), (r, i) => r.GetBoolean(i) },
				{ typeof (byte), (r, i) => r.GetByte(i) },
				{ typeof (byte[]), GetBytes },
				{ typeof (char), (r, i) => r.GetChar(i) },
				{ typeof (char[]), (r, i) => GetBytes(r, i).Cast<char>().ToArray() },
				{ typeof (DateTime), (r, i) => r.GetDateTime(i) },
				{ typeof (decimal), (r, i) => r.GetDecimal(i) },
				{ typeof (double), (r, i) => r.GetDouble(i) },
				{ typeof (float), (r, i) => r.GetFloat(i) },
				{ typeof (Guid), (r, i) => r.GetGuid(i) },
				{ typeof (short), (r, i) => r.GetInt16(i) },
				{ typeof (int), (r, i) => r.GetInt32(i) },
				{ typeof (long), (r, i) => r.GetInt64(i) },
				{ typeof (string), (r, i) => r.GetString(i) }
			};

		/// <summary>
		/// 	Gets the specified record value.
		/// </summary>
		/// <param name = "record">The record.</param>
		/// <param name = "columnName">Name of the column.</param>
		/// <returns></returns>
		public static object Get(this IDataRecord record, string columnName)
		{
			return record.Get(typeof (object), columnName);
		}

		/// <summary>
		/// 	Gets the specified record value.
		/// </summary>
		/// <param name = "record">The record.</param>
		/// <param name = "ordinal">The ordinal.</param>
		/// <returns></returns>
		public static object Get(this IDataRecord record, int ordinal)
		{
			return record.Get(typeof (object), ordinal);
		}

		/// <summary>
		/// 	Gets the specified record value.
		/// </summary>
		/// <typeparam name = "T"></typeparam>
		/// <param name = "record">The record.</param>
		/// <param name = "columnName">Name of the column.</param>
		/// <returns></returns>
		public static T Get<T>(this IDataRecord record, string columnName)
		{
			return Try.Get(() => (T) record.Get(typeof (T), columnName));
		}

		/// <summary>
		/// 	Gets the specified record value.
		/// </summary>
		/// <typeparam name = "T"></typeparam>
		/// <param name = "record">The record.</param>
		/// <param name = "ordinal">The ordinal.</param>
		/// <returns></returns>
		public static T Get<T>(this IDataRecord record, int ordinal)
		{
			return Try.Get(() => (T) record.Get(typeof (T), ordinal));
		}

		/// <summary>
		/// 	Gets the specified record value.
		/// </summary>
		/// <param name = "record">The record.</param>
		/// <param name = "columnType">Type of the column.</param>
		/// <param name = "columnName">Name of the column.</param>
		/// <returns></returns>
		public static object Get(this IDataRecord record, Type columnType, string columnName)
		{
			int? index = Try.Get(() => record.GetOrdinal(columnName) as int?);
			return index.HasValue ? record.Get(columnType, index.Value) : null;
		}

		/// <summary>
		/// 	Gets the specified record value.
		/// </summary>
		/// <param name = "record">The record.</param>
		/// <param name = "columnType">Type of the column.</param>
		/// <param name = "ordinal">The ordinal.</param>
		/// <returns></returns>
		public static object Get(this IDataRecord record, Type columnType, int ordinal)
		{
			if (record.IsDBNull(ordinal))
				return null;

			Func<IDataRecord, int, object> getter = _valueGetters.GetValue(columnType)
				?? new Func<IDataRecord, int, object>((r, i) => r.GetValue(i));

			return Try.Get(() => getter(record, ordinal));
		}

		private static byte[] GetBytes(IDataRecord record, int ordinal)
		{
			var bufferSize = unchecked((int) _dataBufferSize);
			if (bufferSize <= 0)
				throw new InvalidOperationException(string.Format(DataResources.BufferSizeInvalidFormat, _dataBufferSize));

			var buffer = new byte[bufferSize];
			long offset = 0;

			var result = new List<byte>();

			while (true)
			{
				var count = unchecked((int) record.GetBytes(ordinal, offset, buffer, 0, bufferSize));

				if (count <= 0)
					break;

				offset += count;
				result.AddRange(buffer.Take(count));
			}

			return result.ToArray();
		}
	}
}